package com.haha.community.interceptor;

import com.haha.community.entity.LoginTicket;
import com.haha.community.entity.User;
import com.haha.community.service.LoginTicketService;
import com.haha.community.service.UserService;
import com.haha.community.util.CookieUtil;
import com.haha.community.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Yang
 * @date 2020/10/31
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LoginTicketService loginTicketService;
    private static Logger logger = LoggerFactory.getLogger(LoginTicketInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue(request, "ticket");
        if (ticket!=null){
            LoginTicket ticket1 = loginTicketService.findLoginTicketByTicket(ticket);
            if (ticket1!=null&&ticket1.getStatus()==0&&System.currentTimeMillis()<ticket1.getExpired().getTime()){
                //说明有效,获取用户的信息保存起来，存放thread Local中，多线程安全
                User user = userService.getById(ticket1.getUserId());
                logger.info("********查询到用户的id为{}的用户信息存放到thread Local中******",user.getId());
                hostHolder.setUser(user);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        // 放到视图中，然后视图中可以调用相关的信息
        if (user!=null&&modelAndView!=null){
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
